// 获取本地媒体流
export const getLocalMediaStream = async options => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia(options)
    return stream
  } catch (e) {
    console.error('获取本地媒体流失败', e)
  }
}

// 获取屏幕共享流
export const getLocalScreenMediaStream = async options => {
  try {
    const stream = await navigator.mediaDevices.getDisplayMedia(options)
    return stream
  } catch (e) {
    console.log('获取屏幕共享流失败', e)
  }
}

export const setRemoteVideoStream = (video, track) => {
  if (!video) return

  if (video.srcObject) {
    video.srcObject.addTrack(track)
  } else {
    let mediaStream = new MediaStream()
    mediaStream.addTrack(track)
    video.srcObject = mediaStream
  }
}

export const setVideoLocalStream = (video, stream) => {
  if (!video) return
  if (video.srcObject) {
    video.srcObject.getTracks().forEach(track => track.stop())
  }
  video.srcObject = stream
}
export const createPeerConnection = () => {
  const peer = new RTCPeerConnection({
    // bundlePolicy: 'max-bundle',
    // rtcpMuxPolicy: 'require',
    // iceTransportPolicy: 'relay',
    // iceServers: [
    //   {
    //     urls: 'stun:stun.l.google.com:19302'
    //   }
    // ]
  })
  return peer
}

export const createVideoElement = count => {
  const videoContainer = document.querySelector('.video-container')
  const video = document.querySelector(`#video-${count}`)
  if (!video) {
    const video = document.createElement('video')
    video.id = `video-${count}`
    video.autoplay = true
    video.muted = true
    video.controls = true
    videoContainer.appendChild(video)
  }
  return video
}
